﻿/*
 *  item.js
 *
 *  jQuery plugin to handle the creation, update and removal of item equipment records.
 */
(function ($) {
    var settings = {
        updateItemUrl: '',                    // service url of update item ajax call.
        updateItemCallback: null,                 // call back function after item has been updated.
        removeItemLinkSelector: '.remove-item',   // selector for all remove item item links.
        removeItemCallback: null,                 // after item removed event call back function. parameter link = link clicked.
        itemListUrl: '',                                  // service url to refresh item list.
        itemListContainerSelector: '.armour-container',   // selector for item list container.
        refreshItemCallback: null,                        // call back function after item list refreshed.
        equipLinkSelector: '.equip-item',                   // selector for all equip/un-equip links.
        equipItemCallback: null                             // call back function called after item equipped/un-equipped.
    };

    var busy = false;

    var methods = {
        init: function (options) {
            $('.message-box').hide();

            settings = $.extend(settings, options);

            var $this = $(this);

            bindEquipItemEvent();

            bindRemoveItemEvent();

            bindUpdateItemEvents();
        },
        refreshItemList: function () {
            _refreshItemList();
        }

    };


    $.fn.item = function (method) {

        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on item object.');
        }

    };

    /*
    *  Refresh the item list html.
    */
    function _refreshItemList() {
        doAjaxGet(
                    settings.itemListUrl,
                    settings.itemListContainerSelector,
                    function () {

                        //bindUpdateItemEvents();

                        bindRemoveItemEvent();

                        bindEquipItemEvent();

                        if (settings.refreshItemCallback)
                            settings.refreshItemCallback();
                    },
                    showWarning);
    }

    /*
    *  Bind link event handlers for the equip/un-equip action.
    */
    function bindEquipItemEvent() {
        $(settings.equipLinkSelector).click(function (event) {
            event.preventDefault();

            if (busy)
                return;

            busy = true;

            var $this = $(this);
            var equipped = $this.attr('data-equipped');

            equipped = (equipped == "true") ? "false" : "true";

            var url = $this.attr('href');
            url += '?equipped=' + equipped;

            doAjaxGet(url, null,
                    function () {
                        if (settings.equipItemCallback)
                            settings.equipItemCallback();

                        if (equipped)
                            showMessage('Item equipped.');
                        else
                            showMessage('Item un-equipped.');

                        busy = false;
                    },
                    function (data) {
                        if (equipped)
                            showErrorText('Failed to equip item.');
                        else
                            showErrorText('Failed to un-equip item.');

                        showWarning(data);
                        busy = false;
                    });
        });
    }

    /*
    *  Bind events for the remove item anchor.
    */
    function bindRemoveItemEvent() {
        $(settings.removeItemLinkSelector).click(function () {
            event.preventDefault();

            var $this = $(this);

            if (busy)
                return;

            busy = true;

            var url = $this.attr('href');

            doAjaxGet(url, null,
                    function () {
                        if (settings.removeItemCallback)
                            settings.removeItemCallback($this);

                        showMessage('Item removed.');

                        busy = false;
                    },
                    function (data) {
                        showErrorText('Failed to remove item.');
                        showWarning(data);
                        busy = false;
                    });
        });
    }


    function bindUpdateItemEvents() {
        if (!settings.updateItemUrl)
            return;

        // Handle the add adventure record item form submit.
        $('#editItemForm, #editAbilityForm').submit(function (event) {
            event.preventDefault();

            if (busy)
                return;

            busy = true;

            var $this = $(this);

            //var itemId = $('#itemId').val();
            var itemUseType = $('#itemUseType').val();
            var itemName = $('#itemName').val();
            var itemDescription = $('#itemDescription').val();
            var hqId = $('#itemHQID').val();
            var itemCharges = $('#itemCharges').val();
            var itemFrequency = $('#itemFrequency').val();
            var itemIcon = $('#itemIcon').val();

            // validate date and number values.
            var formValid = true;
            var error = '';

            // item id can be empty.

            // usetype must be in correct set of values.
            if (itemUseType != 'Recharges' && itemUseType != 'Unlimited' && itemUseType != 'AlwaysOn' && itemUseType != 'OnceEver' && itemUseType != 'Charged')
                formValid = false;

            // name is required.
            if (!itemName) {
                error = 'An item name is required.';
                formValid = false;
            }

            // description is optional.

            // charges text is optional.

            // frequency text is optional.

            // icon name is required.
            if (!itemIcon) {
                error = 'An item icon is required.';
                formValid = false;
            }

            if (!formValid) {
                showMessage('The form is not valid. ' + error);
                busy = false;
                return;
            }

            var url = settings.updateItemUrl;

            url += '?itemname=' + itemName + '&hqid=' + hqId + '&description=' + itemDescription + '&usetype=' + itemUseType + '&charges=' + itemCharges + '&frequency=' + itemFrequency + '&icon=' + itemIcon;

            doAjaxGet(url, null,
                    function () {
                        if (settings.updateItemCallback)
                            settings.updateItemCallback();

                        showMessage('Item ' + itemName + ' updated.');

                        busy = false;
                    },
                    function (data) {
                        showMessage('Failed to update item ' + itemName + '.');
                        showWarning(data);
                        busy = false;
                    });
        });
    }

})(jQuery);